package com.x.erp.dao;

import com.x.erp.model.MultilevelActivity;
import com.x.framework.dao.BaseDao;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * 多级营销活动信息DAO
 */
@Repository
public class MultilevelActivityDao extends BaseDao {

	private final static String selectMultilevelActivityListSql = "SELECT " +
			"ema.*, " +
			"ec.CAR_TITLE, " +
			"ec.CAR_IMAGE_URL, " +
			"ec.CAR_RETAIL_PRICE, " +
			"ec.CAR_GUIDE_PRICE, " +
			"ec.CAR_MILEAGE, " +
			"ec.CAR_AUTH_STATE, " +
			"ec.CAR_LICENCE_DATE, " +
			"ec.CAR_LICENCE_STATE " +
			"FROM " +
			"erp_multilevel_activity ema, " +
			"erp_car ec " +
			"WHERE " +
			"ema.car_id = ec.CAR_ID ";
	/**
	 * 查询多级营销活动列表
	 * @param multilevelActivity
	 * @return
	 * @throws Exception
	 */
	public List<MultilevelActivity> selectMultilevelActivityList(MultilevelActivity multilevelActivity) throws Exception{
		StringBuilder sql = new StringBuilder(selectMultilevelActivityListSql);
		List<Object> params = new ArrayList<>();
		searchCondition(sql, params, multilevelActivity);
		return this.queryForList(sql.toString(), MultilevelActivity.class, params, multilevelActivity);
	}

	private final static String selectMultilevelActivityNumSql = "SELECT COUNT(ema.ACTIVITY_ID) FROM erp_multilevel_activity ema WHERE 1=1 ";
	/**
	 * 查询多级营销活动数量
	 * @param multilevelActivity
	 * @return
	 * @throws Exception
	 */
	public int selectMultilevelActivityNum(MultilevelActivity multilevelActivity) throws Exception{
		StringBuilder sql = new StringBuilder(selectMultilevelActivityNumSql);
		List<Object> params = new ArrayList<>();
		searchCondition(sql, params, multilevelActivity);
		return this.queryForInt(sql.toString(), params);
	}

	/**
	 * 查询条件
	 * @param sql
	 * @param params
	 * @param multilevelActivity
	 */
	private void searchCondition(StringBuilder sql, List<Object> params, MultilevelActivity multilevelActivity) {
		if(multilevelActivity != null) {
			if(StringUtils.isNotEmpty(multilevelActivity.getActivityId())){
				sql.append("AND ema.ACTIVITY_ID = ? ");
				params.add(multilevelActivity.getActivityId());
			}
			if(multilevelActivity.getActivityLevel() != null){
				sql.append("AND ema.ACTIVITY_LEVEL = ? ");
				params.add(multilevelActivity.getActivityLevel());
			}
			if(multilevelActivity.getActivityState() != null){
				sql.append("AND ema.ACTIVITY_STATE = ? ");
				params.add(multilevelActivity.getActivityState());
			}
			if(StringUtils.isNotEmpty(multilevelActivity.getIsOrderBy())){
				sql.append("ORDER BY " + multilevelActivity.getIsOrderBy() + " DESC ");
			}
		}
	}
}
